﻿unit FrmMain;

interface

uses
  System.IOUtils,
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;

type
  TForm1 = class(TForm)
    pnlMain: TPanel;
    flwpnl2: TFlowPanel;
    lbl1: TLabel;
    edtExcelPath: TEdit;
    flwpnl3: TFlowPanel;
    lbl2: TLabel;
    edtPdfPath: TEdit;
    flwpnl4: TFlowPanel;
    chk1: TCheckBox;
    btnStart: TButton;
    memoLog: TMemo;
    procedure btnStartClick(Sender: TObject);
    procedure edtExcelPathChange(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses
  ExcelToPdfConverter;
{$R *.dfm}

procedure TForm1.btnStartClick(Sender: TObject);
var
  ExcelPath, PdfPath: string;
  BPreserveStructure: Boolean;
begin
  // 1. 获取并清理用户输入
  ExcelPath := Trim(edtExcelPath.Text);
  PdfPath := Trim(edtPdfPath.Text);
  BPreserveStructure := chk1.Checked;

  // 2. 验证输入
  if (ExcelPath = '') or (PdfPath = '') then
  begin
    ShowMessage('请输入完整的 Excel 文件夹路径和 PDF 输出路径。');
    Exit; // 退出过程，不再执行
  end;

  if not TDirectory.Exists(ExcelPath) then
  begin
    ShowMessage('指定的 Excel 文件夹不存在: ' + ExcelPath);
    edtExcelPath.SetFocus; // 将焦点设置回输入框，方便用户修改
    Exit;
  end;

  // 3. 提升用户体验：禁用按钮并给出提示
  btnStart.Enabled := False;
  Screen.Cursor := crHourGlass; // 显示等待光标
  try
    // 4. 核心调用：执行批量转换
    // TExcelToPdfConverter.BatchConvert(ExcelPath, PdfPath, BPreserveStructure);

    memoLog.Clear;
    TExcelToPdfConverter.BatchConvert(edtExcelPath.Text, // 输入文件夹
      edtPdfPath.Text, // 输出文件夹
      chk1.Checked, // 是否保持目录结构
      memoLog // 日志输出控件
      );

  finally
    // 5. 恢复界面状态
    Screen.Cursor := crDefault;
    btnStart.Enabled := True;
  end;
end;

procedure TForm1.edtExcelPathChange(Sender: TObject);
var
  ExcelPath, ParentPath: string;
begin
  ExcelPath := Trim(edtExcelPath.Text);
  if ExcelPath = '' then
  begin
    edtPdfPath.Text := '';
    Exit;
  end;
  // 获取Excel目录的父目录（同级目录的上一级）
  ParentPath := ExtractFilePath(ExcludeTrailingPathDelimiter(ExcelPath));

  // 拼接父目录和"dist"，得到同级的PDF目录
  edtPdfPath.Text := TPath.Combine(ParentPath, 'dist');
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  InitPath: string;
begin
  // 1. 拼接路径：程序所在目录下的 'excel' 文件夹
  InitPath := TPath.Combine(ExtractFilePath(ParamStr(0)), 'excel');

  // 2. 如果文件夹不存在，则创建它
  if not TDirectory.Exists(InitPath) then
  begin
    try
      TDirectory.CreateDirectory(InitPath);
      // 可以在这里添加一个提示，告知用户文件夹已创建
      // ShowMessage('Excel 文件夹已自动创建: ' + InitPath);
    except
      on E: Exception do
      begin
        ShowMessage('无法创建文件夹: ' + E.Message);
      end;
    end;
  end;

  // 3. 将路径显示在输入框中
  edtExcelPath.Text := InitPath;
end;

end.
